﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.EditPages
{
    public partial class EditRepairBox : BasePage
    {
        int boxID;
        string mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            mode = string.IsNullOrEmpty(Request.QueryString[MODE]) ? ADD_MODE : Request.QueryString[MODE];

            if (string.IsNullOrEmpty(Request.QueryString[ID]) && mode != ADD_MODE)
            {
                CloseDlg(0);
                return;
            }

            if (mode != ADD_MODE)
                boxID = int.Parse(Request.QueryString[ID]);
            else
                btnSave.Enabled = false;

            if (!IsPostBack)
            {
                if (mode != ADD_MODE)
                    txtBoxName.Text = POSSystem.BLL.RepairBoxes.GetBoxName(boxID);
            }
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            try
            {
                Save();
                ((Popup)Master).ShowMessage("Saved");
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true); 
            }
            catch (Exception ex)
            {
                POSSystem.BLL.ErrorLog.WriteToFile("EditRepairBox.aspx.cs", "btnSave_OnClick", ex.StackTrace);
                ((Popup)Master).ShowErrorMessage("Error: " + ex.Message);
            }
        }

        private void Save()
        {
            POSSystem.BLL.RepairBoxes box = new POSSystem.BLL.RepairBoxes();
            if (mode == ADD_MODE)
            {
                box.AddNew();
                box.BranchID = Branches.CurrentBranchID;
                box.Deleted = false;
                box.IsFree = true;
            }
            else
                box.LoadByPrimaryKey(boxID);
            box.s_RepairBoxName = txtBoxName.Text;
            box.LastModifiedByUser = SessionUser.ID;
            box.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
            box.Save();
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            try
            {
                Save();
                CloseDlg(1);
            }
            catch (Exception ex)
            {
                POSSystem.BLL.ErrorLog.WriteToFile("EditRepairBox.aspx.cs", "btnSave_OnClick", ex.StackTrace);
                ((Popup)Master).ShowErrorMessage("Error: " + ex.Message);
            }
        }
    }
}